<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="是否订阅" prop="subscribe">
        <el-select v-model="queryParams.subscribe" placeholder="请选择是否订阅" clearable size="small">
          <el-option
            v-for="dict in dict.type.wx_user_subscribe"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关注渠道" prop="subscribeScene">
        <el-select v-model="queryParams.subscribeScene" placeholder="请选择关注渠道" clearable size="small">
          <el-option
            v-for="dict in dict.type.wx_subscribe_scene"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户性别" prop="subscribeScene">
        <el-select v-model="queryParams.sex" placeholder="请选择用户性别" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户标识" prop="openId">
        <el-input
          v-model="queryParams.openId"
          placeholder="请输入用户标识"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关注时间" prop="subscribeTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button type="success"
                 @click="dialogTagging = true; taggingType = 'tagging'"
                 size="small"
                 icon="el-icon-document"
                 v-hasPermi="['wxmp:wxuser:tagging']">打标签
      </el-button>
      <el-button type="warning"
                 @click="dialogTagging = true; taggingType = 'unTagging'"
                 size="small"
                 icon="el-icon-document"
                 v-hasPermi="['wxmp:wxuser:tagging']">去除标签
      </el-button>
      <el-button type="danger"
                 @click="synchroWxUser"
                 size="small"
                 icon="el-icon-refresh"
                 v-hasPermi="['wxmp:wxuser:synchro']">同步用户
      </el-button>
      <el-dialog
        :title='taggingType == "tagging"?"请选择要打的标签":"请选择要去除的标签"'
        :visible.sync="dialogTagging"
        width="30%">
        <el-checkbox-group v-model="checkedTags">
          <el-checkbox v-for="tag in userTagsData" :label="tag.id" :key="tag.id">{{tag.name}}
          </el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogTagging = false">取 消</el-button>
                  <el-button type="primary" @click="toTagging">确 定</el-button>
                </span>
      </el-dialog>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="头像" align="center"  >
        <template slot-scope="scope">
          <el-avatar shape="square" :size="50"  :src="scope.row.headimgUrl"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="用户标识" align="center" prop="openId" />
      <el-table-column label="是否订阅" align="center" prop="subscribe" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wx_user_subscribe" :value="scope.row.subscribe"/>
        </template>
      </el-table-column>
      <el-table-column label="关注渠道" align="center" prop="subscribeScene" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wx_subscribe_scene" :value="scope.row.subscribeScene"/>
        </template>
      </el-table-column>
      <el-table-column label="关注时间" align="center" prop="subscribeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.subscribeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="国家" align="center" prop="country" />
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="语言" align="center" prop="language" />
      <el-table-column label="关注次数" align="center" prop="subscribeNum" />
      <el-table-column label="取消关注时间" align="center" prop="cancelSubscribeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cancelSubscribeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户备注" align="center" prop="remark" />
      <el-table-column label="操作"  fixed="right" width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mp:user:edit']"
          >备注</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="wxMsgDo(scope.row,scope.index)"
            v-hasPermi="['mp:user:remove']"
          >消息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改微信用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入用户备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="用户消息" :visible.sync="dialogMsgVisible" width="40%">
      <WxMsg :wxUserId="wxUserId" v-if="dialogMsgVisible"></WxMsg>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser,synchroWxUser,tagging } from "@/api/mp/user";
import { getTagsList } from '@/api/mp/usertags'
import WxMsg from '@/components/WxMp/WxMsg.vue'
export default {
  name: "MpUser",
  dicts: ['wx_subscribe_scene', 'wx_user_subscribe', 'sys_user_sex', 'news_type'],
  components: {
    WxMsg
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selectionData: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appType: null,
        subscribe: null,
        subscribeScene: null,
        subscribeNum: null,
        openId: null,
        nickName: null,
        sex: null,
        unionId: null,
      },
      // 日期范围
      dateRange: "",
      // 表单参数
      form: {
        remark:null
      },
      // 表单校验
      rules: {
        openId: [
          { required: true, message: "用户标识不能为空", trigger: "blur" }
        ],
      },
      dialogMsgVisible: false,
      wxUserId: '',
      dialogTagging: false,
      checkedTags: [],
      userTagsData: [],
      taggingType: '',
    };
  },
  created() {
    this.listUserTags()
    this.getList();
  },
  methods: {
    /** 查询微信用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRangeWithoutParam(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    listUserTags() {
      getTagsList().then(response => {
        if (response.code == 200) {
          let userTagsData = response.data
          this.userTagsData = userTagsData
          // this.$refs.crud.DIC.tagidList = userTagsData
        } else {
          this.$message.error('获取用户标签出错：' + response.msg)
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        appType: null,
        subscribe: null,
        openId: null,
        nickName: null,
        sex: null,
        city: null,
        country: null,
        province: null,
        phone: null,
        headimgUrl: null,
        delFlag: null,
        remark: null,
        createTime: null,
        updateTime: null,
        updateBy: null,
        createBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectionData = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微信用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改微信用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除微信用户编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 发送消息 */
    wxMsgDo(row) {
      this.wxUserId = row.id
      this.dialogMsgVisible = true
    },
    /** 同步用户 */
    synchroWxUser() {
      this.$confirm('同步用户需要一定时间，用户量越大、用时越久，请耐心等待，勿重复提交；确认此操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        synchroWxUser().then(response => {
          this.tableLoading = false
          if (response.code == 200) {
            this.getList()
          } else {
            this.$message.error('同步微信用户出错：' + response.msg)
          }
        }).catch(() => {
          this.tableLoading = false
        })
        setTimeout(() => {
          if (this.tableLoading) {
            this.tableLoading = false
            this.$alert('同步请求发送成功，系统正在处理中，请稍后刷新查看同步结果，用户量越大用时越久，请耐心等待，勿重复提交', '提示', {
              confirmButtonText: '确定'
            })
          }
        }, 3000)
      }).catch(() => {
      })
    },
    /** 打标签 */
    toTagging() {
      let openIdList = []
      for (let i = 0; i < this.selectionData.length; i++) {
        openIdList.push(this.selectionData[i].openId)
      }
      if (this.checkedTags.length <= 0) {
        this.$message.error('请选择标签')
        return
      }
      if (openIdList.length <= 0) {
        this.$message.error('请选择用户')
        return
      }
      this.tableLoading = true
      tagging({
        taggingType: this.taggingType,
        tagIds: this.checkedTags,
        openIds: openIdList
      }).then(response => {
        this.tableLoading = false
        this.checkedTags = []
        if (response.code == 200) {
          this.getList()
        } else {
          this.$message.error('打标签出错：' + response.msg)
        }
      }).catch(() => {
        this.tableLoading = false
      })
      this.dialogTagging = false
    },
  }
};
</script>
